package logic

import (
	"context"
	"fmt"
	"goodsrpc/cache"
	"goodsrpc/mysql"

	"goodsrpc/goods"
	"goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *goods.RegisterRequest) (*goods.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var u mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&u)
	if u.ID != 0 {
		logx.Info("手机号已被注册")
		return nil, fmt.Errorf("手机号已被注册")
	}
	key := "send_sms" + in.Mobile
	result, err := cache.Rdb.Get(l.ctx, key).Result()
	if err != nil {
		return nil, err
	}
	if result != in.Code {
		logx.Info("短信验证码错误")
		return nil, fmt.Errorf("短信验证码错误")
	}
	user := mysql.User{

		Mobile: in.Mobile,
	}
	mysql.DB.Debug().Create(&user)

	return &goods.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
